<template>
  <div
    v-if="contextmenuConfig.show"
    ref="target"
    class="contextmenu"
    :style="style"
  >
    <ul class="flex gr-6 flex-col">
      <li v-for="(item, key) in menus" :key="key" @click="run(item)">
        {{ item.title }}
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
  import { CSSProperties, computed, ref } from 'vue';
  import { onClickOutside } from '@vueuse/core';
  import {
    IContextmenuConfig,
    IContextmenuData,
    contextmenuConfig,
  } from './contextmenu';

  const target = ref();
  onClickOutside(target, () => {
    contextmenuConfig.value.show = false;
  });
  const run = (item: IContextmenuData) => {
    item.action();
    contextmenuConfig.value.show = false;
  };
  const style = computed((): CSSProperties => {
    if (contextmenuConfig.value.x + 140 > window.innerWidth) {
      contextmenuConfig.value.x = window.innerWidth - 140;
    }
    return {
      left: `${contextmenuConfig.value.x}px`,
      top: `${contextmenuConfig.value.y}px`,
    };
  });

  const menus = computed(() => {
    return contextmenuConfig.value.menus.map((item) => {
      if (contextmenuConfig.value.data) {
        contextmenuConfig.value.menus[1].title = contextmenuConfig.value.data
          .topping
          ? '取消置顶'
          : '置顶';
        contextmenuConfig.value.menus[0].title = !contextmenuConfig.value.data
          .unread
          ? '标记为已读'
          : '标记为未读';
      }
      return item;
    });
  });
</script>

<style lang="scss" scoped>
  .contextmenu {
    width: 140px;
    box-shadow: 0 0 10px 2px #3e3e3e36;
    height: fit-content;
    position: fixed;
    border-radius: 2px;
    background-color: white;
    padding: 8px 0;
    z-index: 10;
    li {
      height: 32px;
      line-height: 32px;
      border-radius: 2px;
      color: #111;
      padding: 0 16px;
      font-size: 14px;
      user-select: none;
    }
  }
</style>
